<template>
  <div class="divBox">
    <el-card class="box-card">
      <div class="components-container">
        <el-form ref="pram" label-width="150px" :model="pram">
          <el-form-item label="标题" prop="title" :rules="[{required:true, message:'请填写标题', trigger:['blur','change']}]">
            <el-input v-model="pram.title" placeholder="标题" maxlength="100"/>
          </el-form-item>

          <el-form-item label="题目类型" :rules="[{required:true, message:'请选择题目类型', trigger:['blur','change']}]">
            <el-radio-group v-model="pram.type" @change="changeRadioType(formItem.type)">
              <el-radio :label="1">单选</el-radio>
              <el-radio :label="2">多选</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="允许漏选" v-if="pram.type == 2" >
            <el-radio-group v-model="pram.sneak" @change="changeRadioType(formItem.sneak)">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="排序" :rules="[{required:true, message:'请输入序号，倒序排列', trigger:['blur','change']}]">
            <el-input-number v-model="pram.sort"></el-input-number>
          </el-form-item>

          <el-form-item label="题目分类" :rules="[{required:true, message:'请选择题目分类', trigger:['blur','change']}]">
            <el-select v-model="pram.cid" placeholder="请选择" style="width:100%;" @change="cidChange">
              <el-option
                v-for="item in categoryTreeData"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <div class="options" v-for="(item,key) in options" :key="'options'+key">
            <el-form-item :label="'选项' + (key+1)"  props="options" >
              <el-input v-model="item.name"></el-input>
            </el-form-item>
            <el-form-item :label="'分数' + (key+1)"  props="options" >
              <el-input-number  v-model="item.score" :min="0" :max="100"></el-input-number>
            </el-form-item>
          </div>

          <el-form-item>
            <el-button type="primary" :loading="loading" @click="handerSubmit('pram')" v-hasPermi="['admin:article:update']">保存</el-button>
            <el-button type="primary" :loading="loading" @click="addReq()" >新增选项</el-button>
            <el-button  @click="back()" >返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import * as categoryApi from '@/api/categoryApi.js'
import * as articleApi from '@/api/article.js'
import { fileImageApi } from '@/api/systemSetting'
import { getToken } from '@/utils/auth'
import {Debounce} from '@/utils/validate'
export default {
  // name: "edit",
  data() {
    return {
      loading:false,
      constants: this.$constants,
      categoryTreeData: [],
      categoryProps: {
        value: 'id',
        label: 'name',
        children: 'child',
        expandTrigger: 'hover',
        checkStrictly: true,
        emitPath: false
      },
      options: [],
      pram: {
        cid: null,
        sort: 0,
        title: null,
        id: null,
        sneak: 1,
        type: 1
        //选项
      },
      editData: {},
      myHeaders: { 'X-Token': getToken() }
    }
  },
  created() {
    this.tempRoute = Object.assign({}, this.$route)
  },
  mounted() {
    console.log(this.$route);
    if(this.$route.params.id){
      this.getInfo()
      this.setTagsViewTitle()
    } else {
      this.options = [];
    }
    this.handlerGetCategoryTreeData()
  },
  methods: {

    //选择题目类型
    cidChange(e){
      console.log(e);
    },

    back(){
      this.$router.back();
    },

    //新增选项
    addReq() {
      this.options.push({
        name: "",
        score: 0
      })
    },
    getInfo (){
      categoryApi.articleInfoApi({id: this.$route.params.id}).then(data => {
          this.editData = data
          this.hadlerInitEditData()
      })
    },
    hadlerInitEditData() {
      if (!this.$route.params.id) return
      this.pram = this.editData
      this.pram.cid = Number.parseInt(this.pram.cid);
      this.options = this.editData.options;
      console.log(this.pram);

    },
    handlerGetCategoryTreeData() {
      categoryApi.listCategroy({ type: 2, status: '' }).then(data => {
        this.categoryTreeData = data.list
        localStorage.setItem('articleClass', JSON.stringify(data.list))
      })
    },
    handerSubmit:Debounce(function(form) {
      this.$refs[form].validate(valid => {
        if (!valid) return
        if (!this.$route.params.id) {
          this.handlerSave()
        } else {
          this.handlerUpdate()
        }
      })
    }),
    handlerUpdate() {
      this.loading = true
      if (this.options.length == 0) {
        return this.$message.error('请新增选项');
      }
      this.pram.options = this.options;
      articleApi.UpdateArticle(this.pram).then(data => {
        this.$message.success('编辑成功')
        this.loading = false
        this.$router.push({ path: '/zou/daySortList' });
      }).catch(()=>{
        this.loading = false
      })
    },
    handlerSave() {
      this.loading = true
      if (this.options.length == 0) {
        return this.$message.error('请新增选项');
      }
      this.pram.options = this.options;
      articleApi.AddArticle(this.pram).then(data => {
        this.$message.success('新增成功')
        this.loading = false
        this.$router.push({ path: '/course/courselist' });
      }).catch(()=>{
        this.loading = false
      })
    },
    setTagsViewTitle() {
      const title = '编辑题目'
      const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.$route.params.id}` })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
  }
}
</script>

<style scoped></style>
